package com.example.basic.cmdprocess;

import java.io.SequenceInputStream;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CmdProcessExecutor {
	
	private static final String TAG = CmdProcessExecutor.class.getName();
	
	private String[] mBreakStrings;
	private String[] mCmds;
	private Process mProcess = null;
	private boolean mLogprint = false;
	private long timeOutMs = 0 ;
	private int index = 0;
	
	private CountDownLatch countDownLatch;
	private InputStreamLineParser lineParser;
	public CmdProcessExecutor(String[] mBreakStrings, String[] mCmds, boolean mLogprint, long timeOutMs) {
		this.mBreakStrings = mBreakStrings;
		this.mCmds = mCmds;
		this.mLogprint = mLogprint;
		this.timeOutMs = timeOutMs;
		countDownLatch = new CountDownLatch(1);
	}
	
	public boolean execute() {
		try {
			for(String cmd:mCmds) {
				if(mProcess == null) {
					if(mLogprint) {
						System.out.println(TAG + ":"+ cmd);
					}
					mProcess = Runtime.getRuntime().exec(cmd);
					
				}else {
					if(mLogprint) {
						System.out.println(TAG + ":"+ cmd);
					}
					mProcess.getOutputStream().write(cmd.getBytes("GBK"));
					mProcess.getOutputStream().flush();
//					Thread.sleep(2000);
				}
			}
//			mProcess = Runtime.getRuntime().exec(mCmds);
			lineParser = new InputStreamLineParser(new SequenceInputStream(mProcess.getInputStream(),
					mProcess.getErrorStream()), countDownLatch, mLogprint, mBreakStrings);
			lineParser.start();
			countDownLatch.await(timeOutMs,TimeUnit.MILLISECONDS);
			return true;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}finally {
			if(lineParser != null) {
				lineParser.interrupt();
			}
			
			if(mProcess != null) {
				mProcess.destroy();
				mProcess = null;
			}
			cancleExector();
		}
	}
	
	public void cancleExector() {
		if(countDownLatch != null) {
			countDownLatch.countDown();
		}
	}

	public List<String> getResult() {
		if(lineParser != null) {
			return lineParser.getResult();
		}
		return null;
	}
}
